const httpResult = require("../lib/httpResult");
const _ = require("lodash");
let router = require('koa-router')();
const MyEmitter = require('../lib/MyEmitter');
const sendMethod = require('../lib/hxtxChannel').send;
const utils = require("../lib/utils");

const status = {
  MT : {
    Invalid_Parameter : 'Invalid.Parameter',
    Verification_Fail : 'Verification.Fail',
    INVALID_TS : '-1004',
    TS_TIMEOUT : '-1005',
    INVALID_TOKEN : '-1006',
    AUTH_FAIL : '-1007',
    INVALID_ORI_IP : '-1008',
    ACCOUNT_BALANCE_NOT_ENOUGH : '-2001',
    ACCOUNT_CLOSED : '-2002',
    ACCOUNT_NOT_IN_SERVICE_TIME : '-2003',
    MISS_DEST : '-2301',
    INVALID_DEST : '-2302',
    MISS_CONTENT : '-2501',
    CONTENT_OVER_LENGTH : '-2502',
    CONTENT_NOT_MATCH : '-2505',
    DEST_OVER_LENGTH : '-2303'
  }
}

let sender = new MyEmitter(10, sendMethod, async (result) => {console.log(result)});
sender.name = 'iqiyi_sms_send_thread';
sender.startup();

router.get('/', async function (ctx, next) {
  ctx.state = {
    title: 'CAINIAO'
  };

  await ctx.render('index', {
  });
})

async function commonValid(ctx){
  let body = ctx.request.body;
  let account = body.supplier;
  let ts = body.timestamp;
  let token = body.signature;

  //valid acount
  ctx.assert(account, status.MT.Invalid_Parameter);
  ctx.assert(ts, status.MT.Invalid_Parameter);
  ctx.assert(token, status.MT.Invalid_Parameter);
  let customer = await models.customer.findOne({account : account});
  if(!customer){
    throw status.MT.Invalid_Parameter//账号不存在
  }

  let signature = utils.getSignature(body, customer.password)
  // ctx.assert(signature === body.signature, status.MT.Verification_Fail);
  log.info(body.signature, signature, '验证通过：', signature === body.signature)
  return customer;
}

async function doSubmit(ctx){
  // let admin = ctx.session.admin;
  log.info('submit info: ', ctx.request.body);

  let body = ctx.request.body;
  let reqLog = await models.mtRequestLog.create({body});

  let customerInfo = await commonValid(ctx);

  let account = body.account;

  let dest = body.phoneNumber;
  ctx.assert(dest, status.MT.MISS_DEST);

  let content = body.content;
  let ref = body.requestId;

  let fee = utils.feeCount(content);

  let mt_record = {
    request_id : reqLog._id,
    account: customerInfo.account,
    mobile: body.phoneNumber,
    content,
    charge_count : fee,
    ref,
    mt_msg_id : '',
    ext : body.extend,
  }

  let record = await models.mtMsg.create(mt_record);
  record.password = customerInfo.password;
  record.ext = '';
  sender.addTask(record);

  return {
    code : 'OK',
    message : '请求成功',
    smsSize : fee,
    bizId : reqLog._id,
    requestId : ref
  };
}

router.get('/submit', httpResult.respCN(() => {
  throw({code : 405, message: 'METHOD NOT ALLOWED'});
}));

router.post('/submit', httpResult.respCN(doSubmit));

module.exports = router;
